package com.ruoyi.project.business.domain.ruleengine;

import com.ruoyi.project.business.domain.entity.MonthScheduleEmp;
import com.ruoyi.project.business.domain.entity.ScheduleDefineMirror;
import com.ruoyi.project.business.domain.exceptions.RuleException;
import com.ruoyi.project.business.domain.model.JudgeResult;
import com.ruoyi.project.business.domain.model.month.EmpDailySchedule;
import com.ruoyi.project.business.domain.model.month.MonthScheduleSolution;
import com.ruoyi.project.business.domain.model.month.ShiftDefine;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 普通的排班引擎(日排班)
 */
@Slf4j
public class CommonMonthScheduleAssignEngine {
    @Setter
    private List<MonthScheduleEmp> emps;
    @Setter
    private List<ShiftDefine> aimShifts;

    @Setter
    private List<ScheduleDefineMirror> scheduleDefines;

    private MonthScheduleSolution solution = new MonthScheduleSolution();

    public MonthScheduleSolution tryAssign() {
        if (CollectionUtils.isEmpty(emps)) {
            throw new RuleException("错误的排班目标");
        }

        if (CollectionUtils.isEmpty(aimShifts)) {
            throw new RuleException("错误的排班日期");
        }

        for (Iterator<ShiftDefine> shiftDefineIterator = aimShifts.iterator(); shiftDefineIterator.hasNext();) {
            ShiftDefine shift = shiftDefineIterator.next();
            ArrayList<MonthScheduleEmp> empsCopy = new ArrayList<>(emps);
            for (Iterator<MonthScheduleEmp> empIterator = empsCopy.iterator(); empIterator.hasNext();) {
                MonthScheduleEmp emp = empIterator.next();
                emp.setShift(shift);
                emp.setScheduleDefines(scheduleDefines);
                JudgeResult result = emp.ifAssign(solution);
                if (result.isAccept()) {
                    log.debug("匹配到班次  shift {} :{} , user {}", result.getScheduleDefine().getShiftName(), shift.getAimDate().toString(), emp.getUserId());
                    EmpDailySchedule schedule = new EmpDailySchedule();
                    schedule.setScheduleDefine(result.getScheduleDefine());
                    schedule.setAimDate(shift.getAimDate());
                    schedule.setUserId(emp.getUserId());
                    solution.getAllShifts().add(schedule);
                    // 已匹配上的员工，移除
                    empIterator.remove();
                } else {
//                    log.debug("匹配失败  shiftDate {} user {}  {}", shift.getAimDate().getDayOfMonth(), emp.getUserId(), result.getTips());
                }
            }

        }

        // 普通的排班
        return solution;
    }

}
